﻿using System;
using System.IO;
using System.Json;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;

namespace S1._1_2.Apis
{
    public abstract class HttpApiBase
    {
        protected static HttpClient _httpclient;

        protected const string API_HOST = "http://localhost:52896";


        public HttpApiBase()
        {
            var head = new HttpClientHandler();
            head.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true;

            _httpclient = new HttpClient(head)
            {
                BaseAddress = new Uri(API_HOST)
            };
        }


        protected async Task<JsonObject> HttpRequest(HttpRequestMessage httprequest)
        {
            var request = await _httpclient.SendAsync(httprequest);

            return (JsonObject)JsonValue.Load(await request.Content.ReadAsStreamAsync());
        }

        protected void Addtoken(HttpRequestMessage request)
        {
            request.Headers.Authorization = new AuthenticationHeaderValue(
            "Basic",
                Convert.ToBase64String(Encoding.UTF8.GetBytes($"staff:BCLyon2024")
                ));

        }

        protected async Task<JsonObject> GetAsync(string url)
        {
            var reqeust = new HttpRequestMessage(HttpMethod.Get, url);

            Addtoken(reqeust);

            return await HttpRequest(reqeust);
        }


        protected async Task<JsonObject> PostAsync(string url, HttpContent content, bool token = true)
        {
            var reqeust = new HttpRequestMessage(HttpMethod.Post, url)
            {
                Content = content
            };

            if (token) Addtoken(reqeust);

            return await HttpRequest(reqeust);
        }

        protected StringContent Content(object obj)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());

            MemoryStream stream = new MemoryStream();

            serializer.WriteObject(stream, obj);

            byte[] databyte = new byte[stream.Length];

            stream.Position = 0;
            stream.Read(databyte, 0, (int)stream.Length);
            string str = Encoding.UTF8.GetString(databyte);

            StringContent cont = new StringContent(str, Encoding.UTF8, "application/json");
            return cont;
        }

    }


}
